/**
 * module:  牲畜信息
 * avator:   渣
 * table:  nc_livestock,nc_pasture,nc_house
 */
var express = require('express');
var router = express.Router();
var zSend = require('./controller');

const db = require('../../../db/db');

router.get('/list', (req, res) => {
    const { currentPage, pageSize, F_Org_Id, F_HouseId, F_State, F_Type_Id, searchVal } = req.query;

    if (!currentPage || !pageSize) {
        return res.send(zSend('参数错误', 400));
    }

    if (isNaN(currentPage) || isNaN(pageSize)) {
        return res.send(zSend('参数错误', 400));
    }

    const parsedPage = parseInt(currentPage);
    const parsedSize = parseInt(pageSize);
    
    if (parsedPage <= 0 || parsedSize <= 0) {
        return res.send(zSend('参数错误', 400));
    }

    // 拼接WHERE子句（用于主查询和计数查询）
    let whereClause = '';
    const values = [];
    
    if (F_Org_Id) {
        whereClause += ' AND l.F_Org_Id = ?';
        values.push(F_Org_Id);
    }
    if (F_HouseId) {
        whereClause += ' AND l.F_HouseId = ?';
        values.push(F_HouseId);
    }
    if (F_State) {
        whereClause += ' AND l.F_State = ?';
        values.push(F_State);
    }
    if (F_Type_Id) {
        whereClause += ' AND l.F_Type_Id = ?';
        values.push(F_Type_Id);
    }
    if (searchVal) {
        whereClause += ' AND (l.F_No LIKE ? OR l.F_Title LIKE ?)';
        values.push(`%${searchVal}%`, `%${searchVal}%`);
    }

    // 计数查询SQL
    const countSql = `
        SELECT COUNT(*) as total 
        FROM nc_livestock as l
        left JOIN nc_pasture as p ON l.F_Org_Id = p.F_Id 
        left JOIN nc_house as h ON l.F_HouseId = h.F_Id
        WHERE 1=1${whereClause}`;

    db.query(countSql, values, (countErr, countResult) => {
        if (countErr) {
            console.error('查询总记录数失败:', countErr);
            return res.send(zSend('服务器内部错误', 500));
        }
        
        const total = countResult[0].total;
        const totalPages = Math.ceil(total / parsedSize);
        const effectivePage = parsedPage > totalPages ? totalPages : parsedPage;
        const offset = effectivePage > 0 ? (effectivePage - 1) * parsedSize : 0;

        // 主查询SQL
        let sql = `
            SELECT l.*,p.F_Title as pastureTitle,h.F_Title as houseTitle
            FROM nc_livestock as l
            left JOIN nc_pasture as p ON l.F_Org_Id = p.F_Id 
            left JOIN nc_house as h ON l.F_HouseId = h.F_Id
            WHERE 1=1${whereClause}
            LIMIT ? OFFSET ?`;
        const paginationValues = [...values, parsedSize, offset];

        db.query(sql, paginationValues, (err, results) => {
            if (err) {
                console.error('查询牲畜列表失败:', err);
                return res.send(zSend('服务器内部错误', 500));
            }
            
            res.send(zSend({
                list: results,
                total: total,
            }));
        });
    });
});
router.post('/add', (req, res) => {
    const {
        F_Org_Id, F_HouseId, F_Type_Id, F_IMEI, F_Title,
        F_Sex, F_State, F_Birthday, F_Csweight, F_Fathor,
        F_Mathor, F_Weight, tzzb, F_Jy, F_Headimg, F_Remark
    } = req.body;
    const F_Id = Date.now();
    if (!F_Org_Id || !F_HouseId || !F_Type_Id || !F_IMEI || !F_Title || !F_Sex || !F_State || !F_Birthday || !F_Csweight || !F_Fathor || !F_Mathor || !F_Weight || !tzzb || !F_Jy || !F_Headimg || !F_Remark) {
        return res.send(zSend('参数错误', 400));
    }
    const sql = `
        INSERT INTO nc_livestock (F_Id, F_Org_Id, F_HouseId, F_Type_Id, F_IMEI, F_Title, F_Sex, F_State, F_Birthday, F_Csweight, F_Fathor, F_Mathor, F_Weight, tzzb, F_Jy, F_Headimg, F_Remark)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    `
    const values = [
        F_Id, F_Org_Id, F_HouseId, F_Type_Id, F_IMEI, F_Title, F_Sex, F_State, F_Birthday, F_Csweight, F_Fathor, F_Mathor, F_Weight, tzzb, F_Jy, F_Headimg, F_Remark
    ];
    db.query(sql, values, (err, result) => {
        if (result.affectedRows > 0) {
            res.send(zSend('添加成功'));
        } else {
            res.send(zSend('服务器内部错误', 500));
        }
    })
});

router.post('/update', (req, res) => {
    const {
        F_Id, F_Org_Id, F_HouseId, F_Type_Id, F_IMEI, F_Title,
        F_Sex, F_State, F_Birthday, F_Csweight, F_Fathor,
        F_Mathor, F_Weight, tzzb, F_Jy, F_Headimg, F_Remark
    } = req.body;

    if (!F_Id ||!F_Org_Id ||!F_HouseId ||!F_Type_Id ||!F_IMEI ||!F_Title ||!F_Sex ||!F_State ||!F_Birthday ||!F_Csweight ||!F_Fathor ||!F_Mathor ||!F_Weight ||!tzzb ||!F_Jy ||!F_Headimg ||!F_Remark) {
        return res.send(zSend('参数错误', 400));
    }

    const sql = `
        UPDATE nc_livestock 
        SET F_Org_Id =?, 
            F_HouseId =?, 
            F_Type_Id =?, 
            F_IMEI =?, 
            F_Title =?, 
            F_Sex =?, 
            F_State =?, 
            F_Birthday =?, 
            F_Csweight =?, 
            F_Fathor =?, 
            F_Mathor =?, 
            F_Weight =?, 
            tzzb =?, 
            F_Jy =?, 
            F_Headimg =?, 
            F_Remark =? 
        WHERE F_Id =?
    `;

    const values = [
        F_Org_Id, F_HouseId, F_Type_Id, F_IMEI, F_Title, F_Sex, F_State, F_Birthday, F_Csweight, F_Fathor, F_Mathor, F_Weight, tzzb, F_Jy, F_Headimg, F_Remark, F_Id
    ];

    db.query(sql, values, (err, result) => {
        if (result.affectedRows > 0) {
            res.send(zSend('更新成功'));
        } else {
            res.send(zSend('服务器内部错误', 500));
        }
    });
});

router.post('/delete', (req, res) => {
    const { F_Id } = req.body;
    if (!F_Id) {
        return res.send(zSend('参数错误', 400));
    }
    const sql = 'DELETE FROM nc_livestock WHERE F_Id = ?';
    db.query(sql, [F_Id], (err, result) => {
        if (result.affectedRows > 0) {
            res.send(zSend('删除成功'));
        } else {
            res.send(zSend('服务器内部错误', 500));
        }
    })
})

module.exports = router;